import style from './index.module.less'
import { Form, Button, Toast, Dialog, Input, TextArea } from 'antd-mobile'
import PageComponent from '@components/pageComponent'
import { getCaseDetailRequest, updateData } from './ajax'
import { awaitWrap, getSearch, getUrlPre, setSearch, strToNum } from '@src/assets/js/tool'
import { useEffect, useState } from 'react'
import { refreshCaseEditVersion } from '@src/redux/reducers/cases'
import { pop } from '@src/redux/reducers/pages'
import { useAppDispatch } from '@src/redux/hook'
import { AddCircleOutline, AudioOutline } from 'antd-mobile-icons'
import { useHistory, useLocation } from 'react-router-dom'

const { Item, useForm } = Form

async function initData (caseid, id, formRef, setData) {
  Toast.show({ content: '加载中', icon: 'loading', duration: 0 })
  const [e, d] = await awaitWrap(getCaseDetailRequest(caseid))
  if (e === null) {
    Toast.clear()
    if (d) {
      setData(d)
      if (id) {
        const items = (d.claim.items || [{ }]).filter(li => li.id === id)
        const o = formRef.getFieldValue('items')
        if (o && o instanceof Array && o.length) {
          items.forEach((li, i) => {
            if (o[i].desc) {
              li.desc = o[i].desc
            }
          })
        }
        formRef.setFieldsValue({
          items
        })
      }
    }
  }
}

// 格式化争议金额
function formatInitData (claim) {
  const { items } = claim
  claim.dispute_amount = 0
  claim.fee_acceptance = 0
  claim.fee_processing = 0
  items.forEach(item => {
    if (strToNum(item.dispute_amount)) {
      claim.dispute_amount += strToNum(item.dispute_amount)
    }
    if (strToNum(item.fee_acceptance)) {
      claim.fee_acceptance += strToNum(item.fee_acceptance)
    }
    if (strToNum(item.fee_processing)) {
      claim.fee_processing += strToNum(item.fee_processing)
    }
  })
}

async function submitHandle (id, caseid, data, d, dispatch) {
  Toast.show({ content: '提交中', icon: 'loading', duration: 0 })
  const claim = JSON.parse(JSON.stringify(data.claim))
  const items = claim.items || []
  let  l = [...items]
  if (id) {
    const i = l.findIndex(li => li.id === id)
    l.splice(i, 1, d.items[0])
  } else {
    l = l.concat(d.items)
  }
  l.forEach(li => {
    delete li.id
  })
  claim.items = l
  formatInitData(claim)
  const [e] = await awaitWrap(updateData(caseid, { claim }))
  if (e === null) {
    Toast.clear()
    Toast.show({ content: '提交成功', icon: 'success' })
    dispatch(refreshCaseEditVersion())
    dispatch(pop())
  }
}

// 分项方法
// async function autoSplit (c) {
//   if (c === null) {
//     return undefined
//   }
//   const items = c.getFieldValue(['items'])
//   const desc = items[0].desc
//   if (desc === undefined || desc === '' || desc === null) {
//     Toast.show({ content: '请求内容不能为空' })
//     return undefined
//   }
//   const list = splitItem(desc)
//   c.setFieldsValue({
//     items: list.map(li => {
//       return {
//         desc: li,
//         dispute_amount: 0
//       }
//     })
//   })
// }

function Main ({ meta: { caseid = '', id = '' } = { case: '', id: '' } }) {
  const h = useHistory()
  const l = useLocation()
  const [formRef] = useForm()
  const dispatch = useAppDispatch()
  const [data, setData] = useState(null)
  // const items = useWatch('items', formRef)
  // const len = useMemo(() => {
  //   return items && items.length || 0
  // }, [items])
  useEffect(() => {
    if (formRef && caseid) {
      initData(caseid, id, formRef, setData)
    }
  }, [caseid, formRef, id])
  useEffect(() => {
    const o = getSearch()
    if (o.result && formRef) {
      const s = decodeURIComponent(o.result)
      const items = formRef.getFieldValue('items')
      if (s) {
        items[0].desc = s
        formRef.setFieldsValue({
          items
        })
      }
    }
  }, [l, formRef])
  return (
    <PageComponent
      title={ id ? '编辑仲裁请求' : '添加仲裁请求' }
      // right={len < 2 && !id ? <a className={style['split-btn']} onClick={() => autoSplit(formRef)}>智能分项</a> : undefined}
      onBack={() => { setSearch(h, { result: '' }); dispatch(pop()) }}
    >
      <Form layout='horizontal'
        className={style.container}
        form={formRef}
        initialValues={{ items: [{}] }}
        onFinish={d => {
          Dialog.confirm({
            title: '您确定要提交吗？',
            onConfirm: () => {
              setSearch(h, { result: '' })
              submitHandle(id, caseid, data, d, dispatch)
            }
          })
        }}
      >
        <Form.Array
          name='items'
          onAdd={operation => operation.add({ })}
          // renderAdd={() => (
          //   !id && (
          //     <Button block className={style.add}>
          //       <AddCircleOutline /> 添加
          //     </Button>
          //   )
          // )}
          // renderHeader={({ index }, { remove }) => (
          //   !id && (
          //     <div className={style['item-header']}>
          //       <span>请求项{index + 1}</span>
          //       {
          //         len > 1 && (
          //           <a onClick={() => remove(index)} style={{ float: 'right' }}>
          //             删除
          //           </a>
          //         )
          //       }
          //     </div>
          //   )
          // )}
        >
          {fields =>
            fields.map(({ index }) => (
              <div className={style.block}>
                <Item name={[index, 'id']} noStyle><span /></Item>
                <div className={style.desc}>
                  <div className={style['audio-btn']} onClick={() => {
                    const city = getUrlPre()
                    // eslint-disable-next-line no-undef
                    if (typeof wx !== 'undefined' && wx.miniProgram) {
                        // eslint-disable-next-line no-undef
                        wx.miniProgram.navigateTo({
                            url: `/pages/voiceToText/simple-voice?fromH5=true&city=${city}`
                        });
                    }
                  }}>
                    <AudioOutline />
                  </div>
                  <Item
                    name={[index, 'desc']}
                    label='请求内容'
                    rules={[{ required: true, message: '请求内容不能为空' }]}
                  >
                    <TextArea placeholder='请输入' autoSize={{ minRows: 3 }} clearable />
                  </Item>
                </div>
                <Item
                  name={[index, 'dispute_amount']}
                  label='争议金额'
                  rules={[{ required: true, message: '争议金额不能为空' }]}
                >
                  <Input placeholder='请输入' type='number' clearable />
                </Item>
              </div>
            ))
          }
        </Form.Array>
        <Item>
          <div className={style.btns}>
            <Button type='submit' color='primary' block>提交</Button>
          </div>
        </Item>
      </Form>
    </PageComponent>
  )
}

export default Main
